//
//  YDBDetailViewController.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/23.
//  Copyright © 2025 杨东宝. All rights reserved.

import Foundation
import EmptyDataSet_Swift

@available(iOS 12.0, *)
class YDBDetailViewController: YDBBaseViewController {
   
    var selectScreen:Screen?
    var deviceModel:DeviceModel?
    var detailViewModel:PhotosDetaiViewModel?
    var vc:TimePickerViewController?
    var isRefreshed = false
    //MARK: - 提示文案
    lazy var tipLab: UILabel = {
        let lab = UILabel.init()
        lab.text = "connect_tip4".localized
        lab.textColor = HexRGB(0x8B8C8D)
        lab.font = DIMENSION_FONT_OF_SIZE(14)
        view.addSubview(lab)
        return lab
    }()
    //MARK: - loading按钮
    lazy var loadingBtn:ContentButton = {
        let messageBtn = ContentButton.init(frame: CGRect(x: DIMENSION_VALUE(10), y: DIMENSION_VALUE(5), width: DIMENSION_VALUE(30), height: DIMENSION_VALUE(30)))
        view.addSubview(messageBtn)
        return messageBtn
    }()
    //MARK: - 菜单按钮
    lazy var rightBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setImage(UIImage(named: "kongzhiqi"), for: .normal)
        btn.addTarget(self, action: #selector(rightBtnClick(_ : )), for: .touchUpInside)
        view.addSubview(btn)
        return btn
    }()
    
    //MARK: - 重连按钮
    lazy var reconnectBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setTitle("connect_btn_title".localized, for: .normal)
        btn.setTitle("stop_connect_btn_title".localized, for: .selected)
        btn.setTitleColor(HexRGB(0x3D4466), for: .normal)
        btn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        btn.addTarget(self, action: #selector(reconnectBtnClick(_ : )), for: .touchUpInside)
        view.addSubview(btn)
        return btn
    }()
    
    //MARK: - 总共数量
    lazy var totoalLab: UILabel = {
        let lab = UILabel.init()
        lab.text = ""
        lab.textColor = HexRGB(0x8B8C8D)
        lab.font = DIMENSION_FONT_OF_SIZE(14)
        view.addSubview(lab)
        return lab
    }()
    
    //MARK: - 连接状态数量
    lazy var statusLab: UILabel = {
        let lab = UILabel.init()
        lab.textColor = HexRGB(0x8B8C8D)
        lab.font = DIMENSION_FONT_OF_SIZE(14)
        lab.numberOfLines = 0
        view.addSubview(lab)
        return lab
    }()
    //MARK: - 添加照片
    lazy var addPhotoBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setTitle("showlocalphotos".localized, for: .normal)
        btn.setTitleColor(HexRGB(0x3D4466), for: .normal)
        btn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        btn.layer.cornerRadius = DIMENSION_VALUE(15)
        btn.layer.borderColor = HexRGB(0x3D4466).cgColor
        btn.layer.borderWidth = 1.0
        btn.addTarget(self, action: #selector(addPhotoBtnClick(_ : )), for: .touchUpInside)
        view.addSubview(btn)
        return btn
    }()
    //MARK: - 更新相册
    lazy var updatePhotoBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setTitle("commit".localized, for: .normal)
        btn.setTitleColor(HexRGB(0xffffff), for: .normal)
        btn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        btn.layer.cornerRadius = DIMENSION_VALUE(20)
        btn.layer.masksToBounds = true
        btn.setBackgroundColor(HexRGB(0x3d4466), forState: .normal)
        btn.addTarget(self, action: #selector(commitBtnClick(_ : )), for: .touchUpInside)
        view.addSubview(btn)
        return btn
    }()
    
    init(selectScreen: Screen? = nil, deviceModel: DeviceModel? = nil) {
        super.init()
        self.selectScreen = selectScreen
        self.deviceModel = deviceModel
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "device_detail".localized
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn)
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        detailViewModel = PhotosDetaiViewModel.init(delegate: self,deviceModel: self.deviceModel, screen: self.selectScreen)
        //状态同步到页面
        detailViewModel?.onStateUpdate = { [weak self] state in
            self?.onstates(state: state)
        }
        setFrames()
    }
    func setFrames() {
        loadingBtn.style = .icon
        tipLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.top.equalToSuperview().offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        
        reconnectBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.top.equalToSuperview().offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        totoalLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.top.equalTo(loadingBtn.snp_bottom)
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        statusLab.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.top.equalTo(loadingBtn.snp_bottom)
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        
        addPhotoBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-20))
            make.bottom.equalToSuperview().offset(-kTabbarSafeBottomMargin)
            make.height.equalTo(DIMENSION_VALUE(40))
            make.width.equalTo(kScreenWidth/2 - DIMENSION_VALUE(30))
        }
        updatePhotoBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(20))
            make.bottom.equalToSuperview().offset(-kTabbarSafeBottomMargin)
            make.height.equalTo(DIMENSION_VALUE(40))
            make.width.equalTo(kScreenWidth/2 - DIMENSION_VALUE(30))
        }
        view.addSubview(tableView)
        tableView.register(PhotoDetailCell.self, forCellReuseIdentifier: "PhotoDetailCell")
        tableView.myh_footer?.isHidden = true
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(statusLab.snp_bottom).offset(DIMENSION_VALUE(5))
            make.bottom.equalTo(updatePhotoBtn.snp_top).offset(DIMENSION_VALUE(-5))
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if !isRefreshed {
            detailViewModel?.getAlubum()
            isRefreshed = true
        }
    }
    override func setupLoadData() {
        totoalLab.text = "yihuoqu".localized + String(describing: detailViewModel!.photoList.count) + "zhangtupian".localized
        detailViewModel?.getAlubum()
    }
}
@available(iOS 12.0, *)
extension YDBDetailViewController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  detailViewModel?.photoList.count ?? 0
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell : PhotoDetailCell = tableView.dequeueReusableCell(withIdentifier: "PhotoDetailCell") as! PhotoDetailCell
        cell.selectionStyle = .none
        cell.currentIndexPath = indexPath
        cell.setModel(model:  detailViewModel!.photoList[indexPath.row])
        cell.delegate = self
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}
}
@available(iOS 12.0, *)
extension YDBDetailViewController:PhotosDetaiViewModelDelegate,PhotoDetailCellDelegate{
    
    func deleteCell(index: IndexPath) {
        
        AlertManager.shared.showAlert(title: "tips".localized,message: "confirmTip2".localized,buttonAction:  {
            self.detailViewModel?.removePhoto(index: index.row)
        })
     
    }
    func refreshCell(index: IndexPath) {
        AlertManager.shared.showConfirm(title: "tips".localized, message: "refreshTip".localized,confirmAction:  { [self] in
            self.detailViewModel?.updatePhotos(index: index.row)
        })
    }
    func refresh(isEnd:Bool) {
        self.tableView.reloadData()
        totoalLab.text = "yihuoqu".localized + String(describing: detailViewModel!.photoList.count) + "zhangtupian".localized
        if isEnd
        {
            self.tableView.myh_header?.endRefreshing()
        }
    }
    //状态监听
    func onstates(state:ConectState){
         statusLab.text = "blue_status1".localized
         switch state {
         case .unknown:
             break
         case .resetting:break
         case .unsupported:
             reconnectBtn.isSelected = false
             stopConnectLoading()
             self.view.showToastCenter(message: "connect_tip6".localized)
             break
         case .unauthorized:
             break
         case .poweredOff:
             self.view.showToastCenter(message: "connect_tip8".localized)
             break //蓝牙关闭
         case .poweredOn: break//蓝牙开启
         case .scanning:
             reconnectBtn.isSelected = true
             startConnectLoading()
             tipLab.text = "connect_tip1".localized + (self.deviceModel?.name ?? "")
             break //扫描中
         case .stopScan:
             break  //停止扫描
         case .noFountDevice:
             reconnectBtn.isSelected = false
             stopConnectLoading()
             self.view.showToastCenter(message: "connect_tip3".localized)
             break //未发现设备
         case .noConnectDevice:
             reconnectBtn.isSelected = false
             stopConnectLoading()
             self.view.showToastCenter(message: "connect_tip9".localized)
             break //未发现设备
         case .connecting:
             reconnectBtn.isSelected = true
             startConnectLoading()
             tipLab.text = "connect_tip1".localized + (self.deviceModel?.name ?? "")
             break //正在连接
         case .connected:
             reconnectBtn.isSelected = true
             stopConnectLoading()
             tipLab.text = "connect_tip5".localized + (self.deviceModel?.name ?? "")
             break  //已连接
         case .disconnecting:
             break //正在断开连接
         case .disconnected:
             reconnectBtn.isSelected = false
             stopConnectLoading()
             tipLab.text = "connect_tip2".localized + (self.deviceModel?.name ?? "")
             break //连接已断开
         case .serviceDiscovering:
             break //正在发现服务
         case .characteristicDiscovering:break //正在发现特征
         case .ready:
             reconnectBtn.isSelected = true
             stopConnectLoading()
             tipLab.text = "connect_tip5".localized + (self.deviceModel?.name ?? "")
             statusLab.text = "blue_status2".localized
             break //已就绪，可发送数据
         case .communication:
             statusLab.text = "blue_status3".localized
             break //正在通信中
         case .complate:
             statusLab.text = "blue_status4".localized
             refresh(isEnd: true)
             break //通信完成
         default: break
         }
    }
}
@available(iOS 12.0, *)
extension YDBDetailViewController{
     //MARK: - 功能按钮
   @objc func rightBtnClick(_ btn :UIButton) {
       // 创建弹窗
       let dialog = SelectionDialogView(
           title: "selectBtn".localized,
           items: toCMDArray(),
           selectedIndex: nil
       ){ selectedIndex in
           AlertManager.shared.showConfirm(title: "tips".localized,message: "confirmTip".localized, confirmAction:  {
               self.confirmAlert(index: selectedIndex)
           })
       }
       // 显示弹窗
       dialog.show()
   }
    func confirmAlert(index:Int){
        switch index {
        case 0:
            vc = TimePickerViewController()
            vc!.onTimeSelected = { [weak self] start,hour,minute,second in
                if start {
                    self?.repeatSet(isStart: start,hour:hour,minite: minute,second: second)
                }else{
                    self?.repeatSet(isStart: start)
                }
            }
            self.navigationController?.pushViewController(vc!, animated: true)
        case 1:
            detailViewModel?.updatePrevPhoto()
        case 2:
            detailViewModel?.updateNextPhoto()
        case 3:
            detailViewModel?.clearPhoto()
        case 4:
            break
        default:
            break
        }
    }
    //开启和关闭循环
    func repeatSet(isStart:Bool,hour:Int? = 0,minite:Int? = 0,second:Int? = 0){
        if isStart {
            detailViewModel?.slideOn(repeatInfo: ReapetInfo(hour: hour!,minute: minite!,second: second!))
        }else{
            detailViewModel?.slideOff()
        }
    }
    //MARK: - 重连按钮
   @objc func reconnectBtnClick(_ btn :UIButton) {
       if reconnectBtn.isSelected {
           reconnectBtn.isSelected = false
           detailViewModel?.closeBlu()
           stopConnectLoading()
       }else{
           reconnectBtn.isSelected = true
           detailViewModel?.getAlubum()
           startConnectLoading()
       }
   }
    func startConnectLoading(){
        loadingBtn.content = .inProgress
        tipLab.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(50))
        }
    }
    func stopConnectLoading(){
        loadingBtn.content = .default
        tipLab.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
        }
    }
    //MARK: - 添加照片
    @objc func addPhotoBtnClick(_ btn :UIButton) {
        
        let  imagePickerVC = DKImagePickerController()
        imagePickerVC.assetType = .allPhotos
        imagePickerVC.showsCancelButton = true
        imagePickerVC.maxSelectableCount = 5
        imagePickerVC.didSelectAssets = {
            assets in
            self.handleSelectAssets(assets)
        }
        present(imagePickerVC, animated: true)
    }

    func handleSelectAssets(_ assets:[DKAsset]) {
        var images = [UIImage]()
       
        for asset in assets {
            asset.fetchOriginalImage { image, info in
                if let img = image {
                    images.append(img)
                    if images.count ==  assets.count{
                        DispatchQueue.main.async {
                            let galleryVC = ImageGalleryViewController(images: images,screen: self.selectScreen!)
                            galleryVC.delegate = self
                            self.navigationController?.pushViewController(galleryVC, animated: true)
                        }
  
                    }
                    
                }
            }
        }
    }
    //MARK: - 更新相册
    @objc func commitBtnClick(_ btn :UIButton) { 
        self.detailViewModel?.updateDevicePhotos()
    }
}
@available(iOS 12.0, *)
extension YDBDetailViewController:ImageGalleryViewControllerDelegate{
    func imageGalleryViewController(_ controller: ImageGalleryViewController, didFinishCroppingImages images: [UIImage]) {
        var arrayList = Array<PhotoInforModel>()
        for image in images {
            arrayList.append(PhotoInforModel(orgImage: image,imageNo_new: self.detailViewModel?.photoList.count))
        }
        detailViewModel?.addPhotosWithImages(photoArray: arrayList)
    }
}
@available(iOS 12.0, *)
extension YDBDetailViewController:EmptyDataSetSource,EmptyDataSetDelegate{
    
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        
        let normalString = "暂无数据"
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 18),
            .foregroundColor: UIColor.gray
        ]
        let attributedString = NSAttributedString(string: normalString, attributes: attributes)
        return attributedString

    }
    func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
        return imageNamed("noOrderIcon")
    }
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return DIMENSION_VALUE(-75)
    }
}
